<?php
declare (strict_types = 1);

namespace app\command\Tongtu;

use app\libs\TongtuSDK\Action\OrderApi;
use app\model\Orders;
use app\model\ShopsPayment;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use function Clue\StreamFilter\fun;

class UploadTrackNum extends Command
{
    protected int $limit = 5;
    /**
     * @var OrderApi
     */
    protected OrderApi $tongtu;
    protected function configure()
    {
        // 指令配置
        $this->setName('upload:tracknum')
            ->addOption('order_id','id',Option::VALUE_OPTIONAL,'订单ID')
            ->addOption('sn','sn',Option::VALUE_OPTIONAL,'订单编号')
            ->addOption('sid','sid',Option::VALUE_OPTIONAL,'店铺ID')
            ->setDescription('上传通途单号');
    }

    protected function execute(Input $input, Output $output)
    {
        $options = $input->getOptions();
        $this->tongtu = new OrderApi();
        //1.获取订单列表
        foreach (range(1,99999) as $page){
            $offset = ($page - 1) * $this->limit;
            dump('****************正字处理第'. $page .'页数据');
            $orderList = $this->getOrderList($offset,$options);
            if($orderList->isEmpty()) break;
            //获取追踪号
            $result = $this->getTrackNumList($orderList);
            if(empty($result)) continue;
            $this->uploadTrackNumToPlatform($result);
        }


    }

    protected function getOrderList($offset=1,$options=[])
    {
        return Orders::query()
               //订单ID
               ->when(isset($options['order_id']) && !empty($options['order_id']),function ($q) use ($options){
                   return $q->whereIn('id',explode(',',$options['order_id']));
               })
                 //店铺ID
                ->when(isset($options['sid']) && !empty($options['sid']),function ($q) use ($options){
                    return $q->whereIn('shop_id',explode(',',$options['sid']));
                })
                //订单编号
                ->when(isset($options['sn']) && !empty($options['sn']),function ($q) use ($options){
                    return $q->where('sn',$options['sn']);
                })
                ->where('order_status',Orders::ORDER_STATUS_COMPLETED)
                ->where('is_upload',Orders::ORDER_STATUS_WAIT)
               ->limit($offset,$this->limit)
               ->select();
    }

    /**
     * @param $orderList
     * @return array
     * @desc 获取追踪号
     */
    protected function getTrackNumList($orderList):array
    {
        $list = [];
        $orderList->each(function (Orders $order) use (&$list){
            $list[] = [
                'id'=>$order->id,
                'shop_id'=>$order->shop_id,
                'tongtu_code'=>$order->tongtu_code,
                'payment_id'=>$order->payment_id,
            ];
        });
        $orderIds = array_column($list,'tongtu_code');
        //array_push($orderIds,'8c4eee-1004');
        $result = $this->tongtu->trackingNumberQuery($orderIds);
        $datas = $result['datas'] ?? [];
        if(empty($datas)) return [];
        $trackingNumberList = array_column($datas,'trackingNumber','orderId');
        $res = [];
        foreach ($list as $item){
            if(array_key_exists($item['tongtu_code'],$trackingNumberList)){
                $item['track_num'] = $trackingNumberList[$item['tongtu_code']];
                $res[] = $item;
            }
        }
        return $res;

    }

    //上传跟踪号到平台
    protected function uploadTrackNumToPlatform(array $datas)
    {
        $trackingNumberList = array_column($datas,'track_num','id');
        $orderList = Orders::query()->whereIn('id',array_keys($trackingNumberList))->select();
        $orderList->each(function (Orders $order) use ($trackingNumberList){
            $trackNum = $trackingNumberList[$order->id];
            switch ($order->payment->pay_method){
                case ShopsPayment::PAY_METHOD_PAYPAL:
                    $this->uploadTrackNumToPaypal($order,$trackNum);
                    break;
                case ShopsPayment::PAY_METHOD_ASIABILL:
                    $this->uploadTrackNumToAsiabill($order,$trackNum);
                    break;
            }
        });
    }

    /**
     * @param Orders $order
     * @param string $track_num
     * @return void
     * @desc 上传paypal跟踪号
     */
    protected function uploadTrackNumToPaypal(Orders $order,string $track_num)
    {

    }

    /**
     * @param Orders $order
     * @param string $track_num
     * @return void
     * @desc 上传asiabill跟踪号到asiabill
     */
    protected function uploadTrackNumToAsiabill(Orders $order,string $track_num)
    {

    }



}
